import { reqGetInfo, reqGetUserPhoto, reqLogin } from '@/api/user'
import router, { resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  // 存储token
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 移出token
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 存储用户信息
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  // 移出登录信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录请求
  async login(context, from) {
    const res = await reqLogin(from)
    context.commit('setToken', res.data)
    return res
  },
  // 获取用户信息
  async getUserInfo(context) {
    const { data: data1 } = await reqGetInfo()
    const { data: data2 } = await reqGetUserPhoto(data1.userId)
    // 合并用户数据
    const result = {
      ...data1,
      ...data2
    }
    context.commit('setUserInfo', result)
    return result
  },
  // 登出
  async logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
    router.push('/login')
    // 退出重置路由
    resetRouter()
    // 退出重置vuex中的路由信息
    // 注：在vuex中跨模块调用方法需要加root:true,意思是在全局模块寻找方法
    commit('permission/setRoutes', [], { root: true })
    // 5. 重置主题色
    commit('settings/resetTheme', null, { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
